package com.seari.gena.ciosClient.handler;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class CIOSUpdateClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private String sid;

	public CIOSUpdateClientHandler(String sid) {
		this.sid = sid;
	}

	/**
	 * 向服务端发送数据
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("gena更新通道-开启：" + ctx.channel().localAddress() + "channelActive");
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
		StringBuffer sb = new StringBuffer();
		sb.append("SUBSCRIBE " + "/Train" + " HTTP/1.1\r\n");
		sb.append("Host:" + clientIP + "\r\n");
		sb.append(sid + "\r\n");
		sb.append("Content-Length:0" + "\r\n");
		sb.append("\r\n");
		System.out.println("gena更新准备发送的数据包：" + sb.toString());
		ctx.writeAndFlush(Unpooled.copiedBuffer(sb.toString(), CharsetUtil.UTF_8)); // 必须有flush

	}

	/**
	 * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
	 *
	 */
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("gena更新通道-关闭：" + ctx.channel().localAddress() + "channelInactive");
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		System.out.println("gena更新channelRead");
		ByteBuf buf = msg.readBytes(msg.readableBytes());
		String retunMsg = buf.toString(Charset.forName("UTF-8"));
		System.out.println("更新返回十六进制报文:" + ByteBufUtil.hexDump(buf));
		System.out.println("更新返回报文:" + retunMsg);
		if (retunMsg.contains("200")) {
			System.out.println("更新请求成功");
		} else {
			System.out.println("更新请求失败");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		System.out.println("更新异常退出:" + cause.getMessage());
	}
}